package com.sysware;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

public class FileUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if(!ServletFileUpload.isMultipartContent(request)) return;
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upoad = new ServletFileUpload(factory);
		try {
			List<FileItem> fileList = upoad.parseRequest(request);
			for (FileItem fileItem : fileList) {
				if(!fileItem.isFormField()) {
					System.out.println(fileItem.getName());
					InputStream is = fileItem.getInputStream();
					FileUtils.copyInputStreamToFile(is, new File("d://"+fileItem.getName()));
					is.close();
					fileItem.delete();
				}
			}
			
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}

}
